//
//  RootViewController.m
//  TabPilotEdit
//
//  Created by Scott Guyer on 7/19/08.
//  Copyright __MyCompanyName__ 2008. All rights reserved.
//

#import "EVEApi.h"
#import "BrowserViewController.h"
#import "EditPilotViewController.h"
#import "PilotPickerViewController.h"
#import "AlertManager.h"
#import "defs.h"


@implementation EditPilotViewController


@synthesize userIDCell, userIDText;
@synthesize apiKeyCell, apiKeyText;
@synthesize pilotCell, pilotText;
@synthesize dataIsValid, charList;
@synthesize lookupCell, testCell, testActivity;
@synthesize addAllSwitch, addAllCell;
@synthesize mode;


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil 
{
	if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) 
	{
		charListRequest = nil;
		charList = nil;
		pickingPilot = NO;
		browserVC = nil;
		doingLookup = NO;
		dataIsValid = NO;
		
		NSArray* nibObjects = [[NSBundle mainBundle] loadNibNamed:nibNameOrNil owner:self options:nil];
		if ( nibObjects == nil )
		{
			NSLog(@"%s unable to laod nib", __FUNCTION__);
			return nil;
		}
		
		apiKeyText.clearButtonMode = UITextFieldViewModeWhileEditing;
		apiKeyText.rightViewMode   = UITextFieldViewModeWhileEditing;
		apiKeyText.clearsOnBeginEditing = NO;
		

		
		userIDText.clearButtonMode = UITextFieldViewModeWhileEditing;
		userIDText.rightViewMode   = UITextFieldViewModeWhileEditing;
		userIDText.clearsOnBeginEditing = NO;
		
		UIFont* f = [UIFont fontWithName:@"Georgia" size:13.0];
		[userIDText setFont:f];
		[apiKeyText setFont:f];
		
		[testActivity setHidesWhenStopped:YES];
		[testActivity stopAnimating];
		
		[self.view setAutoresizesSubviews:YES];
	}
	
	return self;
}


- (void) setDataValid:(BOOL)flag
{
	dataIsValid = flag;
	
	if ( flag )
	{
		[testCell setAccessoryType:UITableViewCellAccessoryCheckmark];
	}
	else
	{
		[testCell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
		[pilotText setText:@""];
		WIPE( charList)
	}
}

- (void) revalidate
{
	if ( [self loadCharacters] )
		[testActivity startAnimating];
	else
		[testActivity stopAnimating];
}


- (IBAction) switchValueChanged:(id) sender
{
        NSArray* rows = nil;
 		
		rows = [[NSArray alloc] initWithObjects:[NSIndexPath indexPathForRow:1 inSection:1], nil];
		
        if ( [addAllSwitch isOn] )
			[self.tableView deleteRowsAtIndexPaths:rows withRowAnimation:UITableViewRowAnimationFade];			
        else
			[self.tableView insertRowsAtIndexPaths:rows withRowAnimation:UITableViewRowAnimationFade];
		
        [rows release];
}


- (BOOL)textFieldShouldClear:(UITextField *)textField
{	
	[self setDataValid:NO];
	
	return YES;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
	[self setDataValid:NO];
	
	return YES;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
	return 3;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	switch ( section )
	{
		case 0:
			return 3;
			break;
			
		case 1:
			if ( (mode == EditPilotViewModeAdding) && (! [addAllSwitch isOn]) )
				return 2;
			else
				return 1;			
			break;
			
		case 2:
			return 1;
			break;						
	}
	
	/* should not be reached */
	return 0;
}


- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section 
{
	switch ( section )
	{
		case 0:
			return [NSString stringWithString:@"Edit your account info"];
			break;
		case 1:
			return [NSString stringWithString:@"Select Pilot(s)"];			
			break;
		case 2:
			return [NSString stringWithString:@"Validate Settings"];			
			break;
	}
	
	/* should not be reached */
	return @"";
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{
	// Set up the cell
	UITableViewCell* cell;
	
	switch ( indexPath.section )
	{
		case 0:
			switch ( indexPath.row )
			{
			case 0:
				cell = userIDCell;
				break;
			case 1:
				cell = apiKeyCell;
				break;
			case 2:
				cell = lookupCell;
				break;				
			}
			
			break;
			
		case 1:
			if ( mode == EditPilotViewModeEditing )
				cell = pilotCell;
			else
			{
				if ( indexPath.row == 0 )
					cell = addAllCell;
				else
					cell = pilotCell;
			}
			
			break;
			
		case 2:
			cell = testCell;
			break;
			
	}
		
	return cell;
}


- (void) charactersReplyFrom:(EVEApi*)request withResponse:(id)respObj
{
	[pilotPickerVC.activityView stopAnimating];
	[testActivity stopAnimating];
	
	if ( respObj == nil )
	{
		[[AlertManager sharedAlertManager] alert:AlertManagerAlertType_EVEServiceUnavailable
									  withString:@"Unable to access the character list service at this time."];
		return;		
	}
	else
	{
		if ( charList != nil )
		{
			[charList removeAllObjects];
			[charList release];
		}
		
		charList = (NSMutableDictionary*) respObj;
		[charList retain];
		
		if ( (mode == EditPilotViewModeAdding) && ([addAllSwitch isOn]) )
		{
			if ( [charList count] > 0 )
				[self setDataValid:YES];
		}
		
		[pilotPickerVC setCharactersFromDictionary:charList];
	}
	
	
	[request release];
//	[charListRequest release];
	charListRequest = nil;
}


- (Boolean) loadCharacters 
{	
	if ( charListRequest == nil )
	{
		NSString* user = [userIDText.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
		NSString* api = [apiKeyText.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
		
		if ( ([user length] <= 0) || ([api length] <= 0) )
		{
			UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Invalid Data" 
															message:@"Both User ID and API Key fields must be valid."	
														   delegate:self 
												  cancelButtonTitle:@"OK" 
												  otherButtonTitles:nil];
			[alert show];
			[alert release];
			return NO;
		}
		
		charListRequest = [[EVEApi alloc] initWithUser:user andKey:api];
		if ( charListRequest != nil )
		{
			[charListRequest setResponseDelegate:self];
			[charListRequest getCharacters:@selector(charactersReplyFrom:withResponse:)];			
		}
	}
	
	return YES;
}

- (void) showPilotPickerView
{

	if ( activeResponder != nil )
	{
		[activeResponder resignFirstResponder];
		activeResponder = nil;
	}
		
	if ( ! [self loadCharacters] )
		return;
	
	if ( pilotPickerVC == nil )
	{
		pilotPickerVC = [[PilotPickerViewController alloc] init];	
		pilotPickerVC.editPilotVC = self;
	}
	
	// Clear the pilot list
	[pilotPickerVC setCharactersFromDictionary:nil];
	
	[self.navigationController pushViewController:pilotPickerVC animated:YES];
	[pilotPickerVC.activityView startAnimating];
	
	pickingPilot = YES;
}



 - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{
	 // Navigation logic
	
	switch ( indexPath.section )
	{
		case 0:
			switch ( indexPath.row )
		{
			case 0:
				[userIDText becomeFirstResponder];
				activeResponder = userIDText;
				break;
			case 1:
				[apiKeyText becomeFirstResponder];
				activeResponder = apiKeyText;
				break;
			case 2:
				[self apiLookup:(id)lookupCell];
				break;
		}
			
			break;
			
		case 1:
			if ( mode == EditPilotViewModeEditing )
				[self showPilotPickerView];
			else
			{
				if ( indexPath.row == 1 )
					[self showPilotPickerView];
			}
			
			break;
			
		case 2:
			if ( !dataIsValid && ![testActivity isAnimating] )
				[self revalidate];
			break;			
	}
	
}


- (IBAction) endOnExit:(id)sender
{
	//NSLog(@"%s no yet implemented", __FUNCTION__);
}

- (IBAction) editDidEnd:(id)sender
{
	if ( activeResponder != nil )
		activeResponder == nil;
}



- (void)viewWillAppear:(BOOL)animated 
{
	NSLog(@"%s",__FUNCTION__);
	[super viewWillAppear:animated];
	
	if ( mode == EditPilotViewModeAdding )
		[self.navigationItem setTitle:@"Add Pilot"];
	else
		[self.navigationItem setTitle:@"Edit Pilot"];

	
	// Stupid table view (and others) never takes into account the fact that it is in a tabController.  
	// Hence, we lost 44 pixels in height.
	CGRect f = self.tableView.frame;
	f.size.height = 366;
	[self.tableView setFrame:f];
	
	[self.tableView reloadData];
	
}


- (void)viewDidAppear:(BOOL)animated 
{
	NSLog(@"%s",__FUNCTION__);
	[super viewDidAppear:animated];
	
	if ( doingLookup && (browserVC != nil) )
	{
		doingLookup = NO;
		[self revalidate];
	}
	
	// Only do this when we are in picker mode
	if ( pickingPilot && (pilotPickerVC != nil) )
	{
		pickingPilot = NO;
	
		UITableViewCell* selectedCell = pilotPickerVC.selectedCell;
		if ( selectedCell != nil )
		{
			[pilotText setText:selectedCell.text];
			[self setDataValid:YES];
		}
	}
	
}

- (IBAction) apiLookup:(id)sender
{	
	if ( browserVC == nil )
	{
		browserVC = [[BrowserViewController alloc] initWithNibName:@"BrowserViewController" bundle:nil];
		[browserVC setDelegate:self];
	}
	
	doingLookup = YES;
	
	[browserVC viewWillAppear:YES];
	[self.navigationController pushViewController:browserVC animated:YES];
	[browserVC viewDidAppear:YES];
}


- (void) setUserId:(NSString*)uid 
{
	if ( uid != nil )
	{
		[userIDText setText:uid];
		[self setDataValid:NO];
	}
}

- (void) setApiKey:(NSString*)apiKey 
{
	if ( apiKey != nil )
	{
		[apiKeyText setText:apiKey];
		[self setDataValid:NO];
	}
}


- (IBAction) saveAction:(id)sender 
{
	NSLog(@"%s",__FUNCTION__);	
	
	
	if ( ! dataIsValid )
	{
		NSString* err;
		
		if ( (mode == EditPilotViewModeAdding) && [addAllSwitch isOn] )
		{
			if ( (charList == nil) || ([charList count] <= 0) )
				err = @"No pilots found." ;
		}
		else
		{
			if ( [pilotText.text length] <= 0 )
				err = @"No pilot selected." ;
		}
		
		NSString* msg = [NSString stringWithFormat:@"%@ If you proceed, pilot data will not be saved.  Cancel to correct and revalidate your settings.", err];
		
		UIAlertView* a = [[UIAlertView alloc] initWithTitle:@"Invalid Data" 
													message:msg
												   delegate:self 
										  cancelButtonTitle:@"Cancel" 
										  otherButtonTitles:@"Proceed",nil];
		[a show];
		[a release];
		
		return;
	}
	
	
	// If data was valid, go ahead and pop to save
	[self.navigationController popViewControllerAnimated:YES];
}


- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
	//	NSLog(@"%s buttonIndex: %d", __FUNCTION__, buttonIndex);
	// 0 = cancel, 1 = proceed
	
	if ( buttonIndex == 1 )
	{
		[self.navigationController popViewControllerAnimated:YES];
	}
}

- (void)viewWillDisappear:(BOOL)animated {
		NSLog(@"%s",__FUNCTION__);
}

- (void)viewDidDisappear:(BOOL)animated {
		NSLog(@"%s",__FUNCTION__);
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
	// Return YES for supported orientations
	return (interfaceOrientation == UIInterfaceOrientationPortrait);
}


- (void)didReceiveMemoryWarning {
	[super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
	// Release anything that's not essential, such as cached data
}


- (void)dealloc 
{
	NSLog(@"%s 0x%x", __FUNCTION__, self);
	
	WIPE( userIDCell)
	WIPE( apiKeyCell)
	WIPE( pilotCell)
	WIPE( pilotText)
	WIPE( userIDText)
	WIPE( apiKeyText)
	WIPE( pilotPickerVC)
	WIPE( charListRequest)
	WIPE( charList)	
	WIPE( addAllCell)
	WIPE( addAllSwitch)
	WIPE( testCell)
	WIPE( testActivity)
	
	[super dealloc];
}


@end

